package com.xsoft.demo11;

import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.ItemViewHolder> {
    private List<GoodsInfo> goodsInfos;
    private int layoutId;

    public MyRecyclerAdapter(int layoutId) {
        this.layoutId = layoutId;
    }

    public void bindData(List<GoodsInfo> infos) {
        goodsInfos = infos;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(layoutId, null));
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {
        holder.bindData(goodsInfos.get(position));
    }

    @Override
    public int getItemCount() {
        return goodsInfos == null ? 0 : goodsInfos.size();
    }

    public static class ItemViewHolder extends RecyclerView.ViewHolder {

        private ImageView pictureAlbum;
        private TextView name;
        private TextView price;
        private TextView detail;
        private ImageView picture;

        public ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            pictureAlbum = itemView.findViewById(R.id.picture_album);
            name = itemView.findViewById(R.id.name);
            price = itemView.findViewById(R.id.price);
            detail = itemView.findViewById(R.id.detail);
            picture = itemView.findViewById(R.id.picture);
        }

        public void bindData(GoodsInfo info) {
            name.setText(info.getName());
            price.setText("¥" + info.getPrice());
            detail.setText(info.getDetail());
            try {
                pictureAlbum.setImageBitmap(BitmapFactory.decodeStream(itemView.getContext().getAssets().open(info.getPictureAlbum())));
                if (picture != null) {
                    picture.setImageBitmap(BitmapFactory.decodeStream(itemView.getContext().getAssets().open(info.getPictureAlbum())));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
